import { deleteSync } from "del";
import { ElectronApp, mainResolve, Env } from "./utils";
import gulp from "gulp";
import * as esbuild from "esbuild";
import {consola} from "consola";
import { browserOptions, nodeOptions, getPackConfig } from "./config";
import * as builder from "electron-builder";
import { exec } from "child_process";

//先设置环境变量
Env.getInstance().loadDotEnvRuntime();

async function clean() {
  return deleteSync([
    mainResolve("release"),
  ]);
}

function compileTypescript() {
  exec("npx tsc", (error, _stdout, stderr) => {
    if (error) {
      console.error(`Error: ${error.message}`);
      return;
    }
    if (stderr) {
      console.error(`Stderr: ${stderr}`);
      return;
    }
  });
}


async function watchTask() {
  const app = new ElectronApp();
  console.log("build config", nodeOptions("src/index.ts"))

  const main = await esbuild.context(nodeOptions("src/index.ts"));
  const preload = await esbuild.context(browserOptions("src/preload.ts"));

  const watcher = gulp.watch(["./src"]);
  watcher
    .on("ready", async () => {
      compileTypescript();
      await main.rebuild();
      await preload.rebuild();
      app.start();
    })
    .on("change", async () => {
      compileTypescript();

      await main.rebuild();
      await preload.rebuild();
      app.restart();
    })
    .on("error", (error) => {
      consola.error(error);
    });
  return Promise.resolve();
}

async function buildTask() {
  await esbuild.build(nodeOptions("src/index.ts"));
  await esbuild.build(browserOptions("src/preload.ts"));
}

async function pack() {
  const config = getPackConfig();
  console.log(getPackConfig, config)
  await builder.build({
    config,
    publish: 'always' // 是否生成在线更新用的 latest.yml。如果用github等发布更新，可能还会自动推送更新。
  });
}


export const dev = gulp.series(watchTask);

export const build = gulp.series(buildTask);

export const release = gulp.series(clean, pack);
